<template>
  <div class="info">
    <div>
      <h1>图书详情</h1>
      <form @submit="confirm($event)">
        <input
          type="hidden"
          name="id"
          :value="type === 1 ? '' : BookDetail.id"
        />
        <p>
          书名:<input
            type="text"
            :value="type === 1 ? '' : BookDetail.bookname"
            :disabled="type === 0"
          />
        </p>
        <p>
          作者:<input
            type="text"
            :value="type === 1 ? '' : BookDetail.author"
            :disabled="type === 0"
          />
        </p>
        <p>
          出版社:<input
            type="text"
            :value="type === 1 ? '' : BookDetail.publisher"
            :disabled="type === 0"
          />
        </p>
        <p class="btn">
          <button :disabled="type === 0" type="submit">确认</button>
          <button @click="cancel" type="button">取消</button>
        </p>
      </form>
    </div>
  </div>
</template>
<script>
import { addBook, updateBook, getBook } from "@/api/bookApi/bookApi.js";
export default {
  data() {
    return {};
  },
  props: {
    type: {
      type: Number,
    },
  },
  created() {
    console.log(this.$store.state.book.BookDetail);
  },
  computed: {
    BookDetail() {
      return this.$store.state.book.BookDetail;
    },
  },
  methods: {
    cancel() {
      console.log(11);
      this.$emit("cancel");
    },
    async confirm(e) {
      e.preventDefault();
      if (
        e.target[1].value.trim() === "" ||
        e.target[2].value.trim() === "" ||
        e.target[3].value.trim() === ""
      ) {
        return alert("请填写完整信息");
      }
      if (e.target[0].value) {
        await updateBook({
          id: e.target[0].value,
          bookname: e.target[1].value,
          author: e.target[2].value,
          publisher: e.target[3].value,
        });
      } else {
        await addBook({
          bookname: e.target[1].value,
          author: e.target[2].value,
          publisher: e.target[3].value,
        });
      }
      const res = await getBook();
      // console.log(res.data.data);
      this.$store.commit("book/setBookList", res.data.data);
      this.cancel();
    },
  },
};
</script>
<style lang='less'  scoped>
.info {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.2);
  div {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 200px;
    transform: translate(-50%, -50%);
    background: #fff;
    box-shadow: 2px 2px 5px black;
    justify-content: center;
    align-items: center;
    .btn {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      button {
        width: 80px;
        height: 25px;
      }
    }
  }
}
</style>
